import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'
// import Layout from '@/views/Layout'
// import Detail from '@/views/Detail'
// import Login from '@/views/Login'
// import Register from '@/views/Register'
// import Article from '@/views/Article'
// import Collect from '@/views/Collect'
// import Like from '@/views/Like'
// import User from '@/views/User'
// 按需导入
const Layout = () => {
  return import('@/views/Layout')
}
const Detail = () => import('@/views/Detail')
const Register = () => import('@/views/Register')
const Login = () => import('@/views/Login')
const Article = () => import('@/views/Article')
const Collect = () => import('@/views/Collect')
const Like = () => import('@/views/Like')
const User = () => import('@/views/User')
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/article',
    children: [
      { path: 'article', component: Article },
      { path: 'collect', component: Collect },
      { path: 'like', component: Like },
      { path: 'user', component: User }
    ]
  },
  { path: '/detail/:id', component: Detail },
  { path: '/login', component: Login },
  { path: '/register', component: Register }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    // 登录了
    if (whiteList.includes(to.path)) {
      // 如果已经登陆了 ，再访问登录页 应该跳转到首页
      next('/')
    } else {
      next()
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      // 放行
      next()
    } else {
      // 重新跳转
      next('/login')
    }
  }
})

export default router
